package com.second.app.forkjoin;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @Author GYZ
 * @Date 2024/2/5
 * <pre>
 *  使用RecurseiveTask实现字符串累加
 * </pre>
 */

class MyRecursiveTask extends RecursiveTask<String> {

    private final int beginValue;

    private final int endValue;

    public MyRecursiveTask(int beginValue, int endValue) {
        this.beginValue = beginValue;
        this.endValue = endValue;
    }

    @Override
    protected String compute() {
        System.out.println(Thread.currentThread().getName() + " --------");
        if (endValue - beginValue > 2) {
            int middleValue = (beginValue + endValue) / 2;
            MyRecursiveTask leftTask = new MyRecursiveTask(beginValue, middleValue);
            MyRecursiveTask rightTask = new MyRecursiveTask(middleValue + 1, endValue);
            invokeAll(leftTask, rightTask);
            return leftTask.join() + rightTask.join();
        } else {
            String returnString = "";
            for (int i = beginValue; i < endValue; i++) {
                returnString = returnString + (i);
            }
            System.out.println("else返回：" + returnString + "   " + beginValue + " " + endValue);
            return returnString;
        }
    }
}

public class ExampleOne {
    public static void main(String[] args) throws InterruptedException {
        ForkJoinPool pool = new ForkJoinPool();
        MyRecursiveTask myRecursiveTask = new MyRecursiveTask(1, 20);
        ForkJoinTask<String> forkJoinTask = pool.submit(myRecursiveTask);
        System.out.println(forkJoinTask.join());
        Thread.sleep(5000);
    }
}
